<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

	private $user = false;
	private $attributes = array();
	private $error = '';

	public function __construct($rules = array()) {
		parent::__construct($rules);
		$this->CI->lang->load('label');
	}

	private function loadData($attributes) {
		if (!empty($attributes)) {
			foreach ($attributes as $v) {
				$this->attributes[$v] = $this->CI->input->post($v, true);
			}
		}
	}

	public function __get($name) {
		if (isset($this->$name)) {
			return $this->$name;
		} else {
			return isset($this->attributes[$name]) ? $this->attributes[$name] : false;
		}
	}

	public function validateData($rowData, $rules) {
		$this->loadData($rowData);
		foreach ($rules as $v) {
			if (!isset($this->attributes[$v[0]])) {
				$this->error = $v[0];
				break;
			} else {
				$this->set_rules($v[0], "lang:$v[0]", $v[1]);
				if (!$this->run()) {
					$this->error = validation_errors();
					break;
				}
			}
		}
	}

	public function hasErrors() {
		return empty($this->error) ? false : true;
	}

	public function exist($str, $field)
	{
		sscanf($field, '%[^.].%[^.]', $table, $field);
		return isset($this->CI->db)
		? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() > 0)
		: FALSE;
	}
	
	public function validate_password($password, $param) {
		sscanf($param, '%[^.].%[^.]', $table, $field);
		$user = $this->getUser($table, $field);
		if ($user) {
			if ($user->password_hash == md5(md5($password))) {
				return true;
			}
		}
		return false;
	}

	public function validate_old_password($password, $param) {
		sscanf($param, '%[^.].%[^.]', $table, $field);
		$user = $this->getUser($table, $field);
		if ($user) {
			if ($user->password_hash == md5(md5($password))) {
				return true;
			}
		}
		return false;
	}
	
	public function mobile($mobile) {
		if (preg_match('/^1[0-9]{10}$/', $mobile)) {
			return true;
		} else {
			return false;
		}
	}

	public function captcha($captcha) {
		if(isset($_SESSION['code']) && !empty($_SESSION['code'])) {
			return $_SESSION['code'] == strtolower($captcha);
		}
		return false;
	}
	
	public function cache_matches($cache, $param) {
		$this->CI->load->driver('cache', array('adapter'=>'apc','backup'=>'file'));
		$cache = $this->CI->cache->get($cache);
		if(!$cache) {
			$this->set_message('cache_matches', $this->CI->lang->line('form_validation_cache_matches_overtime'));
			return false;
		} elseif($cache == $this->attributes[$param]) {
			return true;
		} else {
			return false;
		}
	}
	
	private function getUser($table, $field) {
		if ($this->user === false) {
			$value = isset($this->attributes[$field]) ? $this->attributes[$field] : $_SESSION[$field];
			$query = $this->CI->db->from($table)->where(array($field => $value))->get();
			if ($query->num_rows() > 0) {
				$this->user = $query->row();
			}
		}
		return $this->user;
	}

}
